package com.suthund.util;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;

/**
 *
 * Created by yangkang on 2017/3/30.
 */
@Component
public class SendEmailUtil {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static SendEmailUtil sendEmailUtil;

    @PostConstruct
    public void init() {
        sendEmailUtil = this;
    }

    @Value("${sendEmail.username}")
    private String username;

    @Value("${sendEmail.pwd}")
    private String pwd;

    /*默认配置*/
    private final static String UTF = "UTF-8";
    //使用的协议（JavaMail规范要求）
    private final static String JAVA_EMIL = "smtp";
    private final static String TRANSPORT = "mail.transport.protocol";
    private final static String MAIL_HOST = "mail.smtp.host";
    private final static String QQ_EMIL_FORMAT = "smtp.exmail.qq.com";//腾讯邮箱
    //private final static String NETEASE_EMIL_FORMAT = "smtp.163.com";//网易邮箱

    public static void main(String[] args) {
        SendEmailUtil sendEmailUtil = new SendEmailUtil();
        sendEmailUtil.sendEmail("test", "test", "北京165网络科技有限公司");
    }

    /**
     * 发送邮件
     *
     * @param emailContext  邮件内容
     * @param emailSubject  邮件主题
     * @param sendEmailName 收件人姓名
     * @return boolean
     * @auther 杨康
     */
    public boolean sendEmail(String emailContext, String emailSubject, String sendEmailName) {
        Transport transport = null;
        try {
            Properties properties = createProperties();
            Session session = Session.getDefaultInstance(properties);
            session.setDebug(true);
            MimeMessage message;
            message = createMimeMessage(session, emailContext, emailSubject, sendEmailName);
            transport = session.getTransport();
            transport.connect(sendEmailUtil.username, sendEmailUtil.pwd);
            transport.sendMessage(message, message.getAllRecipients());

            logger.debug("{}发送成功", "to manager");
            return true;
        } catch (Exception e) {
            logger.error("[系统异常]:{}", e);
            logger.error("发送邮件失败");
            return false;
        } finally {
            try {
                //  关闭连接
                assert transport != null;
                transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建一封的简单邮件
     *
     * @param session       和服务器交互的会话
     * @param context       邮件文本内容
     * @param emailSubject  邮件主题
     * @param sendEmailName 收件人姓名
     * @return MimeMessage
     * @auther 杨康
     */
    private static MimeMessage createMimeMessage(Session session,
                                                 String context, String emailSubject, String sendEmailName) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sendEmailUtil.username, sendEmailName, UTF));
        String[] args = {"15801399596@163.com"
                , "1017667372@qq.com", "1784449450@qq.com", "3050647129@qq.com", "13399997865@163.com"};
        InternetAddress[] toAll = new InternetAddress[args.length];
        for (int i = 0; i < args.length; i++) {
            toAll[i] = new InternetAddress(args[i], "", UTF);
        }
        message.setRecipients(MimeMessage.RecipientType.TO, toAll);
        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress("yangkang@shoufubx.com", "", "UTF-8"));
        message.setSubject(emailSubject, UTF);
        // 创建消息部分
        BodyPart messageBodyPart = new MimeBodyPart();
        // 消息
        messageBodyPart.setText(context);
        // 创建多重消息
        Multipart multipart = new MimeMultipart();
        // 设置文本消息部分
        multipart.addBodyPart(messageBodyPart);
        // 附件部分
//        messageBodyPart = new MimeBodyPart();
//        DataSource source = new FileDataSource(path);
//        messageBodyPart.setDataHandler(new DataHandler(source));
//        //获取当前时间
//        String nowTime = DateUtil.format(new Date(), "MM月dd日");
//        //获取昨天时间
//        String yesDate = DateUtil.formatYesterday(new Date(), "MM月dd日");
////        messageBodyPart.setFileName(MimeUtility.
////                encodeWord(yesDate + "17点至" + nowTime + "17点" +
////                        sendEmailUtil.fileName + "." + EXCEL_XLSX));
//        multipart.addBodyPart(messageBodyPart);
        message.setSentDate(new Date());
        message.setContent(multipart);
        message.saveChanges();
        return message;
    }

    private static Properties createProperties() {
        Properties props = new Properties();                      // 参数配置
        props.setProperty(TRANSPORT, JAVA_EMIL);                  // 使用的协议（JavaMail规范要求）
        props.setProperty(MAIL_HOST, QQ_EMIL_FORMAT);             // 发件人的邮箱的 SMTP 服务器地址smtp.163.com
//        props.setProperty("mail.smtp.host", "smtp.163.com");    // 发件人的邮箱的 SMTP 服务器地址smtp.163.com
        props.setProperty("mail.smtp.auth", "true");              // 需要请求认证
        return props;
    }
}
